import path from "path";
import fs from "fs";
import Joi from "joi";
//输出真机下载文件到哪里去了
function logFile(req, res, next){
  console.log(req.body.fileSrc)
  res.send({
    code:200,
    msg:req.body.fileSrc
  })
}
//下载apk接口
function file(req, res, next) {
  // console.log(req.path);
  // console.log(req.body);
  if (Object.keys(req.body).length > 0) {
    try {
      const __dirname = path.resolve();
      let a = __dirname + "\\public\\apk";
      const files = fs.readdirSync(a);
      let arr = Object.keys(req.body).map((item) => JSON.parse(item).type);
      if (arr[0] == "apk") {
        let index = files.findIndex(
          (item) => item.split("-")[4].split(".")[1] == "apk"
        );
        let currentfileName = files[index];
        console.log(currentfileName)
        // 读取文件
        fs.readFile(a + "/" + currentfileName, (err, data) => {
          if (err) {
            next(err);
          } else {
            currentfileName = encodeURI(currentfileName, "GBK");
            currentfileName = currentfileName.toString("iso8859-1");
            // res.setHeader("Content-Type", "application/zip");
            var dis_str = "attachment; filename=" + currentfileName;
            res.setHeader("Content-Disposition", dis_str); //必须写这个，不然客户端无法下载正确，且文件会没有名字和后缀，这里就是告诉浏览器这是要下载什么
            res.end(data);
          }
        });
        // fileDisplay(a)
      } else if (arr[0] == "wgt") {
        let index = files.findIndex(
          (item) => item.split("-")[4].split(".")[1] == "wgt"
        );
        let currentfileName = files[index];
        // 读取文件
        fs.readFile(a + "/" + currentfileName, (err, data) => {
          if (err) {
            next(err);
          } else {
            currentfileName = encodeURI(currentfileName, "GBK");
            currentfileName = currentfileName.toString("iso8859-1");
            // res.setHeader("Content-Type", "application/zip");
            var dis_str = "attachment; filename=" + currentfileName;
            res.setHeader("Content-Disposition", dis_str); //必须写这个，不然客户端无法下载正确，且文件会没有名字和后缀，这里就是告诉浏览器这是要下载什么
            res.end(data);
          }
        });
      } else {
        console.log("更新请求传递未知类型参数");
      }
    } catch (error) {
      console.log("参数格式错误!");
    }
  } else {
    console.log("参数未传递!");
  }
}
//检查app是不是最新的
function checkNewApp(req, res, next) {
  const schema = Joi.object().keys({
    version_name: Joi.string().required(),
    version_number: Joi.number().required(),
  });
  const result = Joi.validate(req.body, schema, { allowUnknown: true });
  if (!result.error) {
    const __dirname = path.resolve();
    let a = __dirname + "/public/apk";
    fs.readdir(a, function (err, files) {
      if (err) {
        next(err);
      } else {
        if (files.length > 0) {
          let index = files.findIndex(
            (item) => item.split("-")[4].split(".")[1] == "txt"
          );
          if (index != -1) {
            //获取当前文件的绝对路径
            //对比最新的apk版本
            let fuwuArr = files[index].split("-");
            console.log(fuwuArr,"====",req.body.version_number)

            let clientArr = req.body.version_name.split(".");
            console.log(clientArr)
            if (
              Number(fuwuArr[4].slice(0, fuwuArr[4].length - 4)) <
              req.body.version_number
            ) {
              //通知官方服务器版本号过低
              res.send({
                code: 200,
                msg: "服务器apk版本号过低!",
                data: "1",
                fileName: files[index],
              });
            } else {
              if (
                Number(fuwuArr[1]) == Number(clientArr[0]) &&
                Number(fuwuArr[2]) == Number(clientArr[1]) &&
                Number(fuwuArr[3]) == Number(clientArr[2])
              ) {
                //是最新的，不用更新
                res.send({
                  code: 200,
                  msg: "已是最新的！",
                  data: "1",
                  fileName: files[index],
                });
              } else if (
                Number(fuwuArr[1]) == Number(clientArr[0]) &&
                Number(fuwuArr[2]) == Number(clientArr[1]) &&
                Number(fuwuArr[3]) > Number(clientArr[2])
              ) {
                //小版本跟新
                res.send({
                  code: 200,
                  msg: "小更新！",
                  data: "2",
                  fileName: files[index],
                });
              } else if (
                Number(fuwuArr[1]) > Number(clientArr[0]) ||
                Number(fuwuArr[2]) > Number(clientArr[1])
              ) {
                console.log(Number(fuwuArr[1]) > Number(clientArr[0]),Number(fuwuArr[2]) > Number(clientArr[1]))
                res.send({
                  code: 200,
                  msg: "大更新！",
                  data: "3",
                  fileName: files[index],
                });
              }else{
                res.send({
                  code: 200,
                  msg: "您的版本比服务器apk高，建议联系开发者更新apk文件",
                  data: "1",
                  fileName: files[index],
                });
              }
            }
          } else {
            res.send({
              code: 200,
              msg: "已是最新的！",
              data: "1",
              fileName: "",
            });
          }
        } else {
          res.send({
            code: 200,
            msg: "已是最新的！",
            data: "1",
            fileName: "",
          });
        }
      }
    });
  } else {
    next(result.eror);
  }
}
export { file, checkNewApp,logFile };
